package com.qiaoba.web.util;

import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * IP工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/25 15:49
 */
@Slf4j
public class IpUtil {

    private static Searcher searcher;

    private static final String IPV6_LOCAL_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCAL_IP = "127.0.0.1";

    public static void setSearcher(Searcher searcher) {
        IpUtil.searcher = searcher;
    }

    public static String getIp(HttpServletRequest request) {
        String ip = ServletUtil.getClientIP(request);
        return IPV6_LOCAL_IP.equals(ip) ? LOCAL_IP : ip;
    }

    public static String getIpAddr(String ip) {
        try {
            if (NetUtil.isInnerIP(ip)) {
                return "局域网内IP";
            }
            return searcher.search(ip);
        } catch (Exception e) {
            return "未识别地址";
        }
    }

    public static void closeSearcher() {
        try {
            searcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
